#include "head.h"
int loginFunc(int sockfd){
    int state_is;
    int PASSWD_TRYTIMES=3;
    train_t train_name;//用来传输用户名
    train_t train_password;//用来传输密码
    
    bzero(&train_name,sizeof(train_name));
    bzero(&train_password,sizeof(train_password));

    printf("请输入你的用户名：");
    fgets(train_name.data,sizeof(train_name.data),stdin);
    train_name.data[strlen(train_name.data)-1]='\0';
    train_name.length=strlen(train_name.data);

    printf("请输入你的密码：");
    fgets(train_password.data,sizeof(train_password.data),stdin);
    train_password.data[strlen(train_password.data)-1]='\0';
    train_password.length=strlen(train_password.data);

    //向服务器上传用户名和密码
    send(sockfd,&train_name,sizeof(train_name.length)+train_name.length,MSG_NOSIGNAL);
    send(sockfd,&train_password,sizeof(train_password.length)+train_password.length,MSG_NOSIGNAL);

    while(1){
        recv(sockfd,&state_is,sizeof(int),0);//接受服务器的反馈
        if(state_is==0)return 0;
        if(state_is==1){

            PASSWD_TRYTIMES--;
            if(PASSWD_TRYTIMES==0){
                return -1;//密码尝试多次失败
            }

            printf("请再次尝试你的密码，剩余尝试次数%d：",PASSWD_TRYTIMES);
            bzero(&train_password,sizeof(train_password));
            fgets(train_password.data,sizeof(train_password.data),stdin);
            train_password.data[strlen(train_password.data)-1]='\0';
            train_password.length=strlen(train_password.data);
            send(sockfd,&train_name,sizeof(train_name.length)+train_name.length,MSG_NOSIGNAL);
            send(sockfd,&train_password,sizeof(train_password.length)+train_password.length,MSG_NOSIGNAL);
        }
        else if(state_is==2){
            //用户不存在
            printf("该用户名不存在，请输入正确用户名：");
            bzero(&train_name,sizeof(train_name));
            bzero(&train_password,sizeof(train_password));
            fgets(train_name.data,sizeof(train_name.data),stdin);
            train_name.data[strlen(train_name.data)-1]='\0';
            train_name.length=strlen(train_name.data);

            printf("请重新输入密码：");
            fgets(train_password.data,sizeof(train_password.data),stdin);
            train_password.data[strlen(train_password.data)-1]='\0';
            train_password.length=strlen(train_password.data);

            send(sockfd,&train_name,sizeof(train_name.length)+train_name.length,MSG_NOSIGNAL);
            send(sockfd,&train_password,sizeof(train_password.length)+train_password.length,MSG_NOSIGNAL);
        }

    }
    return 0;
}
